package org.yhhhhhhh.ai_jianli.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.yhhhhhhh.ai_jianli.model.User;
import org.yhhhhhhh.ai_jianli.model.Role;
import org.yhhhhhhh.ai_jianli.service.UserService;
import org.yhhhhhhh.ai_jianli.repository.RoleRepository;

import java.util.List;
import java.util.Set;
import java.util.HashSet;

@Controller
@RequestMapping("/manager")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleRepository roleRepository;

    @GetMapping
    public String showManagerPage(Model model) {
        model.addAttribute("roles", roleRepository.findAll());
        List<User> users = userService.getAllUsers();
        model.addAttribute("users", users);
        model.addAttribute("newUser", new User());
        model.addAttribute("roles", roleRepository.findAll());
        return "manager";
    }

    @PostMapping("/add")
    public String addUser(@ModelAttribute User user,
                          @RequestParam(value = "roleIds", required = false) List<Long> roleIds) {
        Set<Role> roles = roleIds == null ? new HashSet<>() : new HashSet<>(roleRepository.findAllById(roleIds));
        user.setRoles(roles);
        userService.save(user);
        return "redirect:/manager";
    }

    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return "redirect:/manager";
    }

    @PostMapping("/update/{id}")
    public String updateUser(@PathVariable Long id,
                             @ModelAttribute User user,
                             @RequestParam(value = "roleIds", required = false) List<Long> roleIds) {
        User existing = userService.getUserById(id).orElseThrow();
        existing.setUsername(user.getUsername());
        existing.setEmail(user.getEmail());
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            existing.setPassword(user.getPassword());
        }
        Set<Role> roles = roleIds == null ? new HashSet<>() : new HashSet<>(roleRepository.findAllById(roleIds));
        existing.setRoles(roles);
        userService.save(existing);
        return "redirect:/manager";
    }

    @GetMapping("/search")
    public String searchUsers(@RequestParam String keyword, Model model) {
        model.addAttribute("roles", roleRepository.findAll());
        List<User> users = userService.searchUsers(keyword);
        model.addAttribute("users", users);
        model.addAttribute("newUser", new User());
        model.addAttribute("roles", roleRepository.findAll());
        return "manager";
    }
}